<?php

class ElementsController extends FormController
{

  protected $table = 'auto_forms_elements';

  protected $pk = 'element_id';

  protected function initialize()
  {
    parent::initialize();

    $type = new FormElement_Select('element_type', 'Type');
    $type->options = array(
      'text' => 'Text',
      'textarea' => 'Textarea',
      'select' => 'Select'
    );

    $this->Form->addElement($type, Form::ACTION_CREATE | Form::ACTION_INDEX);
    $this->Form->addElement(new FormElement_Text('element_label', 'Label'), Form::ACTION_ALL & ~Form::ACTION_CREATE);
    $this->Form->addElement(new FormElement_Text('element_field', 'Field'), Form::ACTION_ALL & ~Form::ACTION_CREATE);

    $parent = new FormFilter_Select('element_form_id', 'Form');
    $parent->primaryKey = 'form_id';
    $parent->table = 'auto_forms';
    $parent->keyField = 'form_id';
    $parent->labelField = 'form_title';
    $parent->visible = false;
    $parent->required = true;
    $parent->redirect = '/admin/form_builder';

    $this->Form->addFilter($parent);
  }

  protected function createAction()
  {
    if (($output = $this->form(Form::ACTION_CREATE)) === true) {
      s::getInstance()->notices('Record saved');

      return $this->response->redirect(array($this->request->route(), array('action' => 'edit', $this->pk => DB::getInstance()->lastInsertId())));
    }

    return $output;
  }

  protected function editAction()
  {
    $id = $this->Form->getId();

    $row = $this->Form->gateway()->find($id, array('select' => 'element_type'));

    $type = $row['element_type'];

    $s = $this->Form->addElement(new FormSerializer('element_data', ''));

    switch ($type) {
      case 'select':
        $s->addElement(new FormElement_Text('options', 'Options'));
        $s->addElement(new FormElement_Text('options2', 'Options2'));
        break;
    }

    if (($output = $this->form(Form::ACTION_EDIT)) === true) {
      s::getInstance()->notices('Record saved');

      return $this->response->redirect(array($this->request->route(), array('action' => 'edit', $this->pk => $this->Form->getId())));
    }

    return $output;
  }

}
